import {
    login,
    getId
} from '../../api/user.js'
import {
    bindChangeUser,
    getUserInfo
} from '../../api/article.js'

// pages/my/my.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        headUrl: null,
        nick: null,
        user: null,
        isShowLiveAuth: false,
        endTime: "",
        total: '0.00',
        agree: [],
        show: wx.getStorageSync('token'),
        show2: false,
        amount: null,
        bindID: '',
        upID: '',
        disabled:false,
    },
    onChange(event) {
        // event.detail 为当前输入的值
        console.log(event.detail);
        this.setData({
            amount: event.detail
        })
    },
    onClose() {
        this.setData({
            show2: false
        })
    },
    handleOpenTX() {
        this.setData({
            show2: true
        })
    },
    checkboxChange(e) {
        this.setData({
            agree: e.detail.value
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        console.log(options, 'options')
        if (options.id) {
            wx.setStorage({
                key: 'upUser',
                data: options.id
            })
            this.setData({
                upID: options.id
            })
        }
        // 登录状态 传过来的换绑id和本地不一样进行换绑
        // if (wx.getStorageSync('token') && options.bindID && (options.bindID != wx.getStorageSync('bindID'))) {
        //     bindChangeUser({
        //         userId: wx.getStorageSync('user').userId,
        //         upUser: options.bindID
        //     }).then(res => {
        //         console.log(res)
        //         if (!res.status) {
        //             wx.showToast({
        //                 title: '换绑成功',
        //                 icon: 'success',
        //                 duration: 3000
        //             })
        //         }
        //     })
        // }

        if (options.bindID) {
            wx.setStorage({
                key: 'bindID',
                data: options.bindID
            })
            this.setData({
                bindID: options.bindID
            })
        }
        const _this = this
       


    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    async onShow() {
        wx.hideShareMenu()
        this.setData({
            show: wx.getStorageSync('token'),
            nick: wx.getStorageSync('user').nick,
            headUrl: wx.getStorageSync('user').headUrl,
            upID: wx.getStorageSync('upUser'),
            bindID: wx.getStorageSync('bindID'),
        })
        if (wx.getStorageSync('token')) {
            const res = await getUserInfo({
                targetUserId:wx.getStorageSync('user').userId
            })
            if (!res.status) {
                this.setData({
                    user: res.content
                })
            }
        }

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },


    handleOpenVip() {
        this.selectComponent('#vip').open()
    },
    handleOpenXufei() {
        this.selectComponent('#xufei').open()

    },
    handleCall() {
        wx.makePhoneCall({
            phoneNumber: '073185794878',
        })
    },

    author(e) {
        console.log(e)
        // wx.getPrivacySetting({
        //     success: (res) => {
        //         console.log('是否需要授权:', res.needAuthorization);
        //         if (res.needAuthorization) {
        //             console.log('用户尚未同意隐私政策，即将触发原生弹窗');
        //         }
        //     },
        //     fail: (err) => {
        //         console.error('获取隐私设置失败:', err);
        //     }
        // });

        if (e.detail.errMsg === 'getPhoneNumber:ok') {
            this.login(e);
        }
    },
    /**
     * 用户登录
     */
    login(e) {
        // if (!this.data.agree[0]) {
        //     wx.showToast({
        //         title: '请同意隐私政策',
        //         icon: 'none'
        //     })
        //     return
        // }
       

        let _this = this
        this.setData({
            disabled:true
        })
        wx.showLoading({
            title: '登录中',
        })

        var nick = null
        var avatarUrl = null
        wx.getUserInfo({
            desc: '用于完善会员资料和个性化服务',
            success: res => {
                console.log(res, '用户信息')
                nick = res.userInfo.nickName
                avatarUrl = res.userInfo.avatarUrl
                wx.login({
                    timeout: 3000,
                    success: (res) => {
                        wx.setStorageSync('code', res.code);
                        login({
                            code: res.code,
                            encryptedData: e.detail.encryptedData,
                            iv: e.detail.iv,
                            upUser: this.data.bindID ? this.data.bindID : this.data.upID,
                            nick: nick,
                            headUrl: avatarUrl
                        }).then(async res => {
                            wx.hideLoading()
                            this.setData({
                                disabled:false
                            })
                            if (res.content.user) {
                                wx.setStorage({
                                    key: 'token',
                                    data: res.content.token
                                })
                                wx.setStorage({
                                    key: 'user',
                                    data: res.content.user
                                })
                                wx.setStorage({
                                    key: 'isSimpleCourse',
                                    data: res.content.isSimpleCourse
                                })
                                if (wx.getStorageSync('path')) {
                                    wx.reLaunch({
                                        url: wx.getStorageSync('path'),
                                    })
                                } else {
                                    // 登录成功
                                    wx.reLaunch({
                                        url: '/pages/home/home',
                                    })
                                }
                                // 换绑
                                if (wx.getStorageSync('bindID') && wx.getStorageSync('bindID') != res.content.user.userId) {
                                    const result = await bindChangeUser({
                                        userId: res.content.user.userId,
                                        upUser: wx.getStorageSync('bindID')
                                    })
                                    if (!result) {
                                        wx.showToast({
                                            title: '绑定成功',
                                            icon: 'success',
                                            duration: 3000
                                        })
                                    }
                                }
                            }
                        })
                    },
                    fail:()=>{
                        this.setData({
                            disabled:true
                        })
                    }
                })
            },
            fail:(err)=>{
                console.log(err)
                this.setData({
                    disabled:false
                })
                if(err.errno){
                    wx.showToast({
                      title: '请同意隐私政策',
                      icon:'error'
                    })
                }
                wx.hideLoading()
            }
        })


    },
    checkPrivacyStatus() {
        wx.getPrivacySetting({
            success: (res) => {
                console.log('是否需要授权:', res.needAuthorization);
                if (res.needAuthorization) {
                    console.log('用户尚未同意隐私政策，即将触发原生弹窗');
                    // this.triggerPrivacyRelatedApi();
                }
            },
            fail: (err) => {
                console.error('获取隐私设置失败:', err);
            }
        });
    },
    handleShare() {
        wx.showShareMenu()
    },
    handleLogout() {
        wx.removeStorage({
            key: 'token',
        })
        wx.removeStorage({
            key: 'code',
        })
        wx.removeStorage({
            key: 'user',
        })
        this.setData({
            show: null,
            user: null
        })
    },
    handleLink(e) {
        if (!wx.getStorageSync('token')) {
            wx.showToast({
                title: '请登录',
                icon: 'none'
            })
            return
        }
        if (e.currentTarget.dataset.url) {

            wx.navigateTo({
                url: e.currentTarget.dataset.url,
            })
        } else {
            wx.showToast({
                title: '开发中',
                icon: 'none'
            })
        }
    },
    test(e){
        wx.openPrivacyContract({
            success: () => {
              console.log('隐私政策页面打开成功');
            },
            fail: (err) => {
              console.error('打开隐私政策失败', err);
              // 失败处理，如提示用户"无法打开隐私政策"
            }
          });
        console.log(e)
    }

})